package com.bdqn.ch02.SL;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;


import java.io.File;
import java.net.MalformedURLException;
import java.util.Iterator;


/**
 * DOM4JParse
 * 示例7 使用 DOM4J 读取示例二中的收藏信息
 * @aurhor Administrator  whs
 * @since 2024/6/28
 */
public class DOM4JParse {
    public static void main(String[] args) {

//        设置编码格式
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("GBK");

        Document doc = null;
        //加载DOM树
        SAXReader saxReader = new SAXReader();
        try {
            doc = saxReader.read(new File("D:/Frame/frames/web/collectMessage.xml"));
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        // 获取 XML 的根节点
        Element root = doc.getRootElement();
        //遍历所有的 Brand 节点
        for (Iterator iterator = root.elementIterator(); iterator.hasNext();) {
            Element brandEle = (Element) iterator.next();
            //输出 Brand 标签的 name属性的值
            System.out.println("品牌：" +brandEle.attributeValue("name"));
            // 遍历 Type标签
            for (Iterator itType = brandEle.elementIterator();iterator.hasNext();){
                Element typeEle = (Element) itType.next();
                //输出标签的name属性
                System.out.println("\t型号："+typeEle.attributeValue("name"));
            }
        }
    }
}
